package com.web.my12306.controller;

import com.alibaba.fastjson.JSON;
import com.web.my12306.controller.InnerDispatcherController;
import com.web.my12306.dao.IAdminDao;
import com.web.my12306.dao.impl.AdminDaoImpl;
import com.web.my12306.pojo.*;
import com.web.my12306.service.AdminService;
import com.web.my12306.service.impl.AdminServiceImpl;
import com.web.my12306.util.Md5Utils;
import com.web.my12306.util.TextUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class AdminServlet extends InnerDispatcherController
{

    private AdminService adminService = new AdminServiceImpl();

    /*
    * 耿洋
    * 管理员登录
    * 管理员新增
    * 验证码
    * 查看所有管理员
    * 退出登录
    * */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
        //        PrintWriter printWriter = new PrintWriter();
        //        printWriter.append("11111");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        //        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String action = request.getParameter("action");

        if ("login".equals(action))
        {
            doLogin(request, response);
        }

    }

    //自动登录--未完成cookie应用(失败)
    public void autoLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String loginname = "";
        String autoLogin = "";

        Cookie[] cookies = request.getCookies();//取所有的cookie
        if (cookies != null)
        {
            for (Cookie c : cookies)
            {//循环遍历
                if ("loginname".equals(c.getName()))
                {
                    loginname = c.getValue();//从cookie取值保存
                }
                if ("autoLogin".equals(c.getName()))
                {
                    autoLogin = c.getValue();
                }
            }
        }
        //获取表单数据
        Admin admin = new Admin();
        autoLogin = request.getParameter("autoLogin");
        //判断是否自动登录
        if (TextUtils.isEmpty(autoLogin))
        {
            admin.setAutoLogin(false);
        }
        else
        {
            admin.setAutoLogin(true);
        }
        if (TextUtils.isEmpty(loginname) || TextUtils.isEmpty(autoLogin))
        {
            response.sendRedirect(request.getContextPath() + "/admin/admin_login.jsp");
        }
        else
        {
            IAdminDao adminDao = new AdminDaoImpl();
            Admin one = new Admin();
            one.setLoginname(loginname);
            admin = adminDao.findByName(one.getLoginname());//查找管理员是否存在
            if (admin != null && autoLogin.equals(Md5Utils.md5(loginname + "," + admin.getPassword())))
            {
                //保存自动登录的状态
                if (admin.isAutoLogin())
                {
                    //加密保存工号和密码
                    Cookie cL = new Cookie("autoLogin", Md5Utils.md5(one.getLoginname() + "," + one.getPassword()));
                    cL.setMaxAge(60 * 60 * 24);
                    cL.setPath("/");
                    response.addCookie(cL);
                }
                else
                {
                    Cookie cL = new Cookie("autoLogin", "");
                    cL.setMaxAge(0);//删除cL(cookie)
                    cL.setPath("/");
                    response.addCookie(cL);
                }
            }
        }


    }

    //登录
    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        //获取表单数据
        Admin admin = new Admin();
        //从页面获取数据
        admin.setLoginname(request.getParameter("loginname"));
        admin.setPassword(request.getParameter("password"));
        admin.setCode(request.getParameter("codein"));

        if (admin != null)
        {
            HttpSession session = request.getSession();
            String code = (String) session.getAttribute("code");
            if (!code.equalsIgnoreCase(admin.getCode()))
            {//验证码不正确
                String msg = "验证码不正确！";
                request.setAttribute("msg", msg);
                request.getRequestDispatcher("/admin/admin_login.jsp").forward(request, response);
            }
            else
            {

                Admin ad = adminService.login(admin.getLoginname(), Md5Utils.md5(admin.getPassword()));

                if (ad == null)
                {
                    String msg = "登录失败!管理员工号或密码不正确！";
                    request.setAttribute("msg", msg);
                    request.getRequestDispatcher("/admin/admin_login.jsp").forward(request, response);
                }
                else
                {
                    //保存上一次登录的工号
                    Cookie c = new Cookie("loginname", ad.getLoginname());
                    c.setMaxAge(60 * 60 * 24);   //保存一天
                    c.setPath("/");
                    response.addCookie(c);   //响应报头信息

                    //保存admin
                    HttpSession se = request.getSession();
                    se.setAttribute("admin", ad);
                    AccessPrivilege a;
                    if (ad.getRoleid() == 1)
                    {
                        a = new AccessPrivilege(true, null);
                    }
                    else
                    {
                        Set<String> privileges = adminService.queryPriv(ad.getRoleid());
                        a = new AccessPrivilege(false, privileges);
                    }
                    se.setAttribute(CommonConstants.SESSION_PRIVILEGES, a);

                    // 跳转一 ：重定向
                    response.sendRedirect(request.getContextPath() + "/admin/Index.jsp");
                    // 跳转二 :请求转发
                    //                    request.getRequestDispatcher("/admin/Index.jsp").forward(request,response);
                }
            }
        }
        else
        {
            String msg = "登录失败!管理员工号或密码不正确！";
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("/admin/admin_login.jsp").forward(request, response);
        }
    }

    //新增管理员
    public void addAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String l_name = request.getParameter("loginname");
        String l_pass = request.getParameter("password");
        String l_repass = request.getParameter("repassword");
        String l_level = request.getParameter("select");

        Admin check = adminService.findByName(l_name);

        //重名新增
        if (check != null)
        {//有重复
            out.print("<html><head><meta charset='UTF-8'></head>" + "<script>alert('已经存在该管理员!');" + "window.location" +
                    ".href='../admin/addAdmin.jsp'</script>");
        }
        else
        {//没有重复

            //确认密码
            if (l_pass.equals(l_repass))
            {
                //获取表单数据
                Admin admin = new Admin();
                admin.setLoginname(request.getParameter("loginname"));
                admin.setPassword(Md5Utils.md5(request.getParameter("password")));//MD5密码加密
                admin.setRoleid(Integer.valueOf(request.getParameter("select")));

                if (admin != null)
                {
                    adminService.addAdmin(admin.getLoginname(), admin.getPassword(), admin.getRoleid());
                    out.print("<html><head><meta charset='UTF-8'></head>" + "<script>alert('新增管理员成功!')</script>");
                }
                else
                {
                    out.print("<html><head><meta charset='UTF-8'></head>" + "<script>alert('新增管理员失败!');" + "window" +
                            ".location.href='../admin/addAdmin.jsp'</script>");
                }
            }
            else
            {
                out.print("<html><head><meta charset='UTF-8'></head>" + "<script>alert('确认密码不匹配!');" + "window" +
                        ".location.href='../admin/addAdmin.jsp'</script>");
            }
        }
    }

    //验证码
    private static final long serialVersionUID = 1L;
    private char code[] = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'
    };
    private static final int WIDTH = 50;
    private static final int HEIGHT = 20;
    private static final int LENGTH = 4;

    //验证码生成的方法
    public void ValidateCode(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        // 设置响应报头信息
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 设置响应的MIME类型
        response.setContentType("image/jpeg");

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Font mFont = new Font("arival", Font.TRUETYPE_FONT, 18);
        Graphics g = image.getGraphics();
        Random rd = new Random();

        //设置背景颜色
        g.setColor(new Color(rd.nextInt(55) + 200, rd.nextInt(55) + 200, rd.nextInt(55) + 200));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        // 设置字体
        g.setFont(mFont);

        // 画边框
        g.setColor(Color.black);
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
        // 随机产生的验证码
        String result = "";
        for (int i = 0; i < LENGTH; ++i)
        {
            result += code[rd.nextInt(code.length)];
        }
        HttpSession session = request.getSession();
        session.setAttribute("code", result);
        // 画验证码
        for (int i = 0; i < result.length(); i++)
        {
            g.setColor(new Color(rd.nextInt(200), rd.nextInt(200), rd.nextInt(200)));
            g.drawString(result.charAt(i) + "", 12 * i + 1, 16);
        }
        // 随机产生2个干扰线
        for (int i = 0; i < 2; i++)
        {
            g.setColor(new Color(rd.nextInt(200), rd.nextInt(200), rd.nextInt(200)));
            int x1 = rd.nextInt(WIDTH);
            int x2 = rd.nextInt(WIDTH);
            int y1 = rd.nextInt(HEIGHT);
            int y2 = rd.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
        // 释放图形资源
        g.dispose();
        try
        {
            OutputStream os = response.getOutputStream();

            // 输出图像到页面
            ImageIO.write(image, "JPEG", os);
        } catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    //修改密码
    public void editPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //获取登录工号
        HttpSession se = request.getSession();
        Admin admin = (Admin) se.getAttribute("admin");
        //获取数据库里面的密码
        Admin old = adminService.findByName(admin.getLoginname());

        //获取表单数据---新密码
        String oldPassword = request.getParameter("oldPassword");
        String txtNewPass = request.getParameter("txtNewPass");

        //判断原密码是否正确
        if (old.getPassword().equals(Md5Utils.md5(oldPassword)))
        {
            adminService.editPassword(admin.getLoginname(), Md5Utils.md5(txtNewPass));

            //更新session里面的admin对象
            admin.setPassword(Md5Utils.md5(txtNewPass));

            //返回data值
            PrintWriter out = response.getWriter();
            out.print("1");

        }
        else
        {
            PrintWriter out = response.getWriter();
            out.print("2");
            //            String msg = "原密码不正确！";
            //            request.setAttribute("msg", msg);
            //            request.getRequestDispatcher("/admin/editPassword.jsp").forward(request, response);
        }
    }

    //退出登录
    public void exitLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        HttpSession se = request.getSession();
        // 销毁session对象
        //         se.removeAttribute("admin");
        se.invalidate();
        //重定向---返回
        response.sendRedirect(request.getContextPath() + "/admin/admin_login.jsp");
    }

    //查询所有管理员
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //设置行和列
        int page = 0;
        int rows = 0;
        try
        {
            page = Integer.valueOf(request.getParameter("page"));
            rows = Integer.valueOf(request.getParameter("rows"));
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }

        int start = (page - 1) * rows;//page从1开始的，减一，开始数据index
        List<Admin> adminList = adminService.findAll();
        //pageList页面显示的数据的list
        List<Admin> pageList = new ArrayList<>();
        //从所有的列表中取出第start到第start+row即第page页的数据
        //主意循环条件的i<adminList.size()，否则最后一页数据小于rows报错，list越界
        for (int i = start; i < start + rows && i < adminList.size(); i++)
        {
            pageList.add(adminList.get(i));
        }

        EasyUIDataGridJSON responseObject = new EasyUIDataGridJSON();
        responseObject.setTotal(adminList.size());//数据总数，方便显示有多少页，限制页面超出
        responseObject.setRows(pageList);//页面显示数据的list

        response.setContentType("application/json");
        response.getWriter().append(JSON.toJSONString(responseObject));
    }

    //查询所有用户（普通用户）
    public void findAllUser(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //设置行和列
        int page = 0;
        int rows = 0;
        try
        {
            page = Integer.valueOf(request.getParameter("page"));
            rows = Integer.valueOf(request.getParameter("rows"));
        } catch (NumberFormatException e)
        {
            e.printStackTrace();
        }

        int start = (page - 1) * rows;//page从1开始的，减一，开始数据index
        List<User> list = adminService.findAllUser();
        List<User> pageList = new ArrayList<>();
        for (int i = start; i < start + rows && i < list.size(); i++)
        {
            pageList.add(list.get(i));
        }

        EasyUIDataGridJSON responseObject = new EasyUIDataGridJSON();
        responseObject.setTotal(list.size());//数据总数，方便显示有多少页，限制页面超出
        responseObject.setRows(pageList);//页面显示数据的list

        response.setContentType("application/json");
        response.getWriter().append(JSON.toJSONString(responseObject));


    }

    //根据管理员工号删除
    public void deleteAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        //处理中文
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        Admin admin = new Admin();
        //从页面获取数据
        //        admin.setAid(Integer.valueOf(request.getParameter("aid")));
        admin.setLoginname(request.getParameter("loginname"));
        System.out.println(admin.getLoginname());
        if (admin.getAid() != 0)
        {
            //选中删除对象
            adminService.delete(admin.getLoginname());
            //返回data值
            out.print("1");
        }
        else
        {
            out.print("2");

        }


    }

    //测试
    public void lll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("<html><head><meta charset='UTF-8'></head>" + "<script>alert('测试!')</script>");
    }
}
